from flask import Flask, jsonify
from flask_sqlalchemy import SQLAlchemy
from app.config import config
from app.utils.logger import setup_logger
import traceback

db = SQLAlchemy()

def create_app(config_name='default'):
    app = Flask(__name__, 
        static_url_path='/static',
        static_folder='static')
    
    try:
        # 配置应用
        app.config.from_object(config[config_name])
        config[config_name].init_app(app)
        
        # 初始化扩展
        db.init_app(app)
        
        # 设置日志
        setup_logger(app)
        
        # 注册路由
        with app.app_context():
            try:
                # 确保数据库表存在
                db.create_all()
                
                from app.routes.admin import admin
                app.register_blueprint(admin)
                
                # 添加错误处理
                @app.errorhandler(500)
                def internal_error(error):
                    app.logger.error(f'Server Error: {str(error)}')
                    app.logger.error(traceback.format_exc())
                    return jsonify({
                        'error': 'Internal Server Error',
                        'message': str(error)
                    }), 500
                
                @app.errorhandler(404)
                def not_found_error(error):
                    app.logger.error(f'Not Found: {str(error)}')
                    return jsonify({
                        'error': 'Not Found',
                        'message': str(error)
                    }), 404
                
                # Print routes for debugging
                app.logger.info("Registered routes:")
                for rule in app.url_map.iter_rules():
                    app.logger.info(f"{rule.endpoint}: {rule.rule}")
                    
            except Exception as e:
                app.logger.error(f"Error during app context: {str(e)}")
                app.logger.error(traceback.format_exc())
                raise
                
    except Exception as e:
        print(f"Error creating app: {str(e)}")
        print(traceback.format_exc())
        raise
        
    return app 